<?php	namespace Home\Model;
use Hdphp\Model\Model;
/**
 * 前台用户管理模型
 */
class User extends Model
{
	protected $table = 'user';
	//自动验证
	public $validate = array(
		array('username','email','请输入正确邮箱',3,3),
		array('password','user:6,25 ','密码长度在6-25字符',3,3),
		array('code','required','请输入验证码',3,3),
	);
	/**
	 * 注册
	 */
	public function reg()
	{	//执行自动验证
		if(!$this->create())  return false;	
		//验证两次输入密码是否一致
		if(Q('post.password') != Q('post.passworded'))
		{
			$this->error = '两次输入密码不一致';return false;
		}
		//验证验证码
		if(Q('post.code','','strtoupper') != $_SESSION['code']){
			$this->error = '验证码错误,请重新输入';return false;
		}		
		$data = array(
			'username'=>Q('post.username'),
			'password'=>Q('post.password','','md5'),
			'restime'=>time()
		);	
		$this->add($data);
		return true;	
	}
	/**
	 * 登陆控制器
	 */
	public function login()
	{
		$this->validate = array(
			array('username','email','账号必须为邮箱',3,3),
			array('password','user:6,25 ','密码长度在6-25字符',3,3),		
		);
		//执行自动验证
		if(!$this->create())  return false;
		//用户提交的用户名和密码
		$username = Q('post.username');
		$password = Q('post.password','','md5');
		//查询该条用户讯息
		$userInfo = $this->where("username",$username)->first();
		//用户名不正确,执行
			if(!$userInfo){
				$this->error = '用户名错误';
				return false;
			}
		//密码不正确			
			if($password != $userInfo['password']){
				$this->error = '密码错误';
				return false;
			}	
		return $userInfo;				
	}
	/**
	 * 修改个人资料
	 */
	public function edit($uid)
	{
		$this->validate=array(
			array('phonenumber','required','请填写手机号',3,3),
			array('name','required','请填写姓名',3,3),
			array('sex','required','请选择性别',3,3),
			array('address','required','请填写详细地址',3,3),
			array('postcode','required','请填写邮政编码',3,3),
		);	
		//自动验证
		if(!$this->create())  return false;	
		if($_POST['area'][0]== '0')
		{
			$this->error = '请选择所在地区';return false;
		}
		$area = implode('/', Q('post.area'));
		$data = array(
			'phonenumber'=>Q('post.phonenumber'),
			'name'=>Q('post.name'),
			'sex'=>Q('post.sex'),
			'address'=>Q('post.address'),
			'postcode'=>Q('post.postcode'),
			'area'=>$area,		
		);	
		
		$this->where("uid",$uid)->update($data);
		return true;	
	}
}
